import React, { useCallback, useMemo } from 'react';
import { Modal, Form, Input } from 'antd';
import _ from 'lodash';

interface EditModalProps {
  loading: boolean;
  showModal: boolean;
  setShowModal: Function;
  initValue: string;
  form: any;
  onSubmit: (name: string) => void;
  companyViews: any[];
  customViews: any[];
  viewType: 'custom' | 'company';
}

const EditModal = (props: EditModalProps) => {
  const {
    loading,
    showModal,
    setShowModal,
    initValue = '',
    form: { getFieldDecorator, validateFieldsAndScroll },
    onSubmit,
    companyViews,
    customViews,
    viewType,
  } = props;

  const onOk = useCallback(
    (e: any) => {
      e.stopPropagation();
      validateFieldsAndScroll((errors: any, values: any) => {
        if (errors) return;
        onSubmit && onSubmit(values.name);
      });
    },
    [onSubmit],
  );

  const stoppropagation = useCallback((e) => {
    if (e) {
      e.stopPropagation();
      e.nativeEvent.stopImmediatePropagation();
    }
  }, []);

  const rules = useMemo(() => {
    const allNames = (viewType == 'company' ? companyViews : customViews).map((item) => item.name);

    return [
      {
        message: tr('视图名称重复!'),
        validator: function (rule: any, value: string = '', callback: Function) {
          const res = value.trim();
          if (!res) {
            rule.message = tr('视图名称必填');
            callback(true);
          } else if (allNames.includes(res)) {
            callback(true);
          }
          callback(undefined);
        },
      },
    ];
  }, [companyViews, customViews, viewType]);

  return (
    <div onMouseDown={stoppropagation} onDoubleClick={stoppropagation} style={{ display: 'inline-block' }}>
      <Modal
        title={tr('视图名称修改')}
        visible={showModal}
        destroyOnClose
        centered
        onCancel={setShowModal.bind(null, false)}
        zIndex={1040}
        onOk={onOk}
        confirmLoading={loading}
        okButtonProps={{ size: 'small' }}
        cancelButtonProps={{ size: 'small' }}
      >
        <Form layout="horizontal">
          <Form.Item>
            {getFieldDecorator('name', {
              initialValue: initValue,
              rules: rules,
            })(<Input placeholder={tr('请输入视图名称')} maxLength={500} />)}
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Form.create()(EditModal);
